/*
 * Playlist.java
 *
 * 07/11/2009
 */
package kg.sound.player.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import kg.sound.player.Model;
import kg.sound.player.ModelListener;


/**
 * @author fernando
 */
abstract class ListModelAdapter implements ModelListener, ListModel {

	protected final Model model;
	protected final List<ListDataListener> listeners = new ArrayList<ListDataListener>();

	protected List<File> files;

	private ListModelAdapter(Model model) {
		this.model = model;
		model.getListeners().add(this);
		contentsChanged();
	}
	
	abstract protected Iterator<File> iterator();

	@Override
	abstract public void playlistChanged();

	@Override
	abstract public void clipStarted();

	@Override
	abstract public void clipStopped();

	public void contentsChanged() {
		List<File> itens = new ArrayList<File>();

		Iterator<File> it = iterator();
		while (it.hasNext())
			itens.add(it.next());

		Collections.sort(itens);
		
		files = itens;
		notificarAlteracao();
	}

	@Override
	public Object getElementAt(int index) {
		return files.get(index);
	}

	@Override
	public int getSize() {
		return files.size();
	}

	@Override
	public void addListDataListener(ListDataListener l) {
		listeners.add(l);
	}

	@Override
	public void removeListDataListener(ListDataListener l) {
		listeners.remove(l);
	}

	void notificarAlteracao() {
		ListDataEvent e = new ListDataEvent(this,
				ListDataEvent.CONTENTS_CHANGED, 0, getSize());
		for (ListDataListener l : listeners) {
			l.contentsChanged(e);
		}
	}

	static class Playlist extends ListModelAdapter {

		Playlist(Model model) {
			super(model);
		}

		@Override
		protected Iterator<File> iterator() {
			return model.playlist();
		}

		@Override
		public void playlistChanged() {
			contentsChanged();
		}

		@Override
		public void clipStarted() {
		}

		@Override
		public void clipStopped() {
		}
		
	}

	static class PlayingNow extends ListModelAdapter {

		PlayingNow(Model model) {
			super(model);
		}

		@Override
		protected Iterator<File> iterator() {
			return model.playingNow();
		}

		@Override
		public void playlistChanged() {
		}

		@Override
		public void clipStarted() {
			contentsChanged();
		}

		@Override
		public void clipStopped() {
			contentsChanged();
		}
		
	}
}
